package com.juyu.miliao.scheduler.config;

import com.juyu.miliao.common.dataSource.key.DataSourceKeyEvaluator;
import com.juyu.miliao.common.exception.InternalServerErrorException;
import com.juyu.miliao.common.exception.ResourceNotFoundException;
import com.juyu.miliao.scheduler.dao.redis.UserRedisDao;
import com.juyu.miliao.scheduler.domin.Withdrawals;

public class GlobalDataSourceKeyEvaluator implements DataSourceKeyEvaluator {
    private UserRedisDao userRedisDao;

    public GlobalDataSourceKeyEvaluator(UserRedisDao userRedisDao) {
        this.userRedisDao = userRedisDao;
    }

    @Override
    public String strategy(String strategy, Object param) {
        if ("byUserId".equals(strategy)) {
            return getDataSourceKeyByUserId((Long) param);
        } else if ("byUsername".equals(strategy)) {
            return getDataSourceKeyByUserId(userRedisDao.getUserIdByUserName((String) param)
                    .orElseThrow(() -> new ResourceNotFoundException("用户名不存在")));
        } else if ("byOpenId".equals(strategy)) {
            return getDataSourceKeyByUserId(userRedisDao.getUserIdByOpenId((String) param)
                    .orElseThrow(() -> new ResourceNotFoundException("openId不存在")));
        } else if ("byWithdrawals".equals(strategy)) {
            return getDataSourceKeyByUserId(((Withdrawals) param).getUserId());
        }
        if ("byVideoId".equals(strategy)) {
            return getDataSourceKeyByUserId(Long.parseLong(param.toString()));
        } else
            throw new InternalServerErrorException("strategy 类型不支持：" + strategy);
    }

    private String getDataSourceKeyByUserId(long userId) {
        return "miliao-user-" + (long) userId % 100;
    }

}
